<script setup lang="js">
import { useSettingsStore } from '@/store';
import * as VTable from '@visactor/vtable';

defineOptions({ name: 'ProVTable' });

const props = defineProps({
  height: {
    type: [String, Number],
    default: 500,
  },
  records: {
    type: Array,
    default: () => [],
  },
  columns: {
    type: Array,
    default: () => [],
  },
  frozenColCount: {
    type: Number,
    default: 1,
  },
  bottomFrozenRowCount: {
    type: Number,
    default: 1,
  },
  rowSeriesNumber: {
    type: Object,
    default: () => ({
      width: 70,
      title: '序号',
      headerStyle: { textAlign: 'center' },
      style: { textAlign: 'center' },
    }),
  },
  select: {
    type: Object,
    default: () => ({
      outsideClickDeselect: true,
    }),
  },
  keyboardOptions: {
    type: Object,
    default: () => ({
      copySelected: true,
      pasteValueToCell: false, // 是否可粘贴到单元格
      selectAllOnCtrlA: true,
      moveEditCellOnArrowKeys: true,
    }),
  },
  tooltip: {
    type: Object,
    default: () => ({
      isShowOverflowTextTooltip: true,
      overflowTextTooltipDisappearDelay: 150,
    }),
  },
  emptyTip: {
    type: Object,
    default: () => ({
      text: '暂无数据',
    }),
  },
  theme: {
    type: Object,
    default: () => {
      return VTable.themes.DEFAULT;
    },
  },
  aggregation: {
    type: Function,
    default: () => '',
  },
  aggregationFields: {
    type: Array,
    default: () => [],
  },
});

const settingsStore = useSettingsStore();
const isDark = computed(() => settingsStore.isDark);

const fields = computed(() => props.aggregationFields);
const aggregation = (args) => {
  if (fields.value?.includes(args.field)) {
    return {
      aggregationType: VTable.TYPES.AggregationType.SUM,
      formatFun(value) {
        if (sumObj.value?.has(args.field)) {
          return sumObj.value?.get(args.field);
        }
        return value;
      },
    };
  }
  return null;
};

const sumObj = ref(new Map());

const tableEl = useTemplateRef('tableEl');

let tableInstance = null;

const currentTheme = computed(() => {
  return isDark.value ? VTable.themes.DARK : props.theme || VTable.themes.DEFAULT;
});

const tableOptions = computed(() => {
  const { aggregationFields, theme, ...restProps } = props;
  return {
    ...restProps,
    theme: currentTheme.value,
    aggregation,
  };
});
watch(
  [() => props.columns, () => props.records],
  ([_cols, _recs]) => {
    if (tableInstance) {
      tableInstance.updateOption({
        ...tableOptions.value,
        columns: _cols,
        records: _recs,
      });
    }
  },
  { deep: true, immediate: true }
);
watch(
  currentTheme,
  (newTheme) => {
    setTimeout(() => {
      tableInstance?.updateTheme(newTheme);
    }, 0);
  },
  { immediate: true }
);

const { SELECTED_CELL, SELECTED_CLEAR } = VTable.ListTable.EVENT_TYPE;
onMounted(() => {
  tableInstance = new VTable.ListTable(tableEl.value, tableOptions.value);
  tableInstance.on(SELECTED_CELL, (arg) => {
    const cellInfos = tableInstance.getSelectedCellInfos();
    sumObj.value.clear();
    cellInfos.forEach((rows) => {
      rows?.forEach((colItem) => {
        const { value, field, cellLocation, originData } = colItem;
        if (cellLocation !== 'body' || originData === undefined) return;
        if (!sumObj.value.has(field)) {
          if (isNaN(Number(value))) {
            return;
          }
          sumObj.value.set(field, value);
        } else {
          sumObj.value.set(field, sumObj.value.get(field) + value);
        }
      });
    });
    console.log('sumObj', sumObj.value);
    tableInstance.updateOption(tableOptions.value);
  });
  tableInstance.on(SELECTED_CLEAR, (...args) => {
    console.log(SELECTED_CLEAR, args);
    sumObj.value.clear();
    tableInstance.updateOption(tableOptions.value);
  });
});
</script>

<template>
  <section ref="tableEl" :style="{ height: height + 'px' }" />
</template>
